package com.asen.commons.utils;

import com.asen.commons.constants.BaseConstant;
import com.asen.commons.exception.TokenInvalidException;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.lang.System.out;
import static java.util.regex.Pattern.compile;

/**
 * @author : Lesao
 * @version : 2018/9/13
 * @Description : http请求工具类
 */
@Slf4j
public class HttpRequestUtil {
//
//    private static RedisCache redisCache = SpringUtil.getBean(RedisCache.class);
//    private static JwtTokenUtil jwtTokenUtil = SpringUtil.getBean(JwtTokenUtil.class);

    // this is config
    private static final String REQ_ENCODEING_UTF8 = "utf-8";
    private static PoolingHttpClientConnectionManager httpClientConnectionManager;

    private static final String AK = "kyL9Mp2jKvTBxFWENHq6fp78";


    static {
        httpClientConnectionManager = new PoolingHttpClientConnectionManager();
        httpClientConnectionManager.setMaxTotal(100);
        httpClientConnectionManager.setDefaultMaxPerRoute(20);
    }

    /**
     * 根据请求获取远程ip地址
     *
     * @return
     */
    public static String getRemoteAddr() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            return null;
        }
        HttpServletRequest request = requestAttributes.getRequest();
        String remoteAddr = request.getHeader("X-Real-IP");

        if (StringUtils.isEmpty(remoteAddr)) {
            return request.getRemoteAddr();
        } else {
            if (StringUtils.isNotEmpty(request.getHeader("X-Forwarded-For"))) {
                remoteAddr = request.getHeader("X-Forwarded-For");
            }

            if (StringUtils.isBlank(remoteAddr) && StringUtils.isNotEmpty(request.getHeader("Proxy-Client-IP"))) {
                remoteAddr = request.getHeader("Proxy-Client-IP");
            }

            if (StringUtils.isBlank(remoteAddr) && StringUtils.isNotEmpty(request.getHeader("WL-Proxy-Client-IP"))) {
                remoteAddr = request.getHeader("WL-Proxy-Client-IP");
            }

            if (StringUtils.isBlank(remoteAddr)) {
                remoteAddr = request.getHeader("X-Real-IP");
            }
        }

        // 多次反向代理后会有多个ip值，第一个ip才是真实ip
        if (StringUtils.isNotEmpty(remoteAddr) && remoteAddr.indexOf(",") != -1) {
            remoteAddr = remoteAddr.split(",")[0];
        }

        return remoteAddr != null ? remoteAddr : request.getRemoteAddr();
    }


    /**
     * 获取发起请求的浏览器名称
     */
    /*public static String getBrowserName() {

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            return null;
        }
        HttpServletRequest request = requestAttributes.getRequest();

        String header = request.getHeader("User-Agent");
        UserAgent userAgent = UserAgent.parseUserAgentString(header);
        Browser browser = userAgent.getBrowser();
        return browser.getName();
    }*/

    /**
     * 获取发起请求的浏览器版本号
     */
    //public static String getBrowserVersion() {
    //
    //    ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    //    if (requestAttributes == null) {
    //        return null;
    //    }
    //    HttpServletRequest request = requestAttributes.getRequest();
    //
    //    String header = request.getHeader("User-Agent");
    //    UserAgent userAgent = UserAgent.parseUserAgentString(header);
    //    //获取浏览器信息
    //    Browser browser = userAgent.getBrowser();
    //    //获取浏览器版本号
    //    Version version = browser.getVersion(header);
    //    return version.getVersion();
    //}

    /**
     * 获取发起请求的操作系统名称
     */
    //public static String getOsName() {
    //    ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    //    if (requestAttributes == null) {
    //        return null;
    //    }
    //    HttpServletRequest request = requestAttributes.getRequest();
    //
    //    String header = request.getHeader("User-Agent");
    //    UserAgent userAgent = UserAgent.parseUserAgentString(header);
    //    OperatingSystem operatingSystem = userAgent.getOperatingSystem();
    //    return operatingSystem.getName();
    //}

    /**
     * 获取远程登录物理地址
     *
     * @return
     */
    //public static String getLocaltion() {
    //    String remoteAddr = getRemoteAddr();
    //    if (StringUtils.isEmpty(remoteAddr)) {
    //        return "未知地址";
    //    }
    //    try {
    //        String url = "https://api.map.baidu.com/location/ip?ak=" + AK + "&coor=bd09ll&ip=" + remoteAddr;
    //        String s = HttpRequestUtil.httpGet(url, null);
    //        JSONObject parse = (JSONObject) JSONObject.parse(s);
    //        String status = parse.getString("status");
    //        if (!"0".equals(status)) {
    //            return "未知地址";
    //        }
    //        String address = parse.getJSONObject("content").getString("address");
    //        return address;
    //
    //    } catch (Exception e) {
    //        log.error("", e);
    //        return "未知地址";
    //    }
    //
    //}

    /**
     * 判断IP地址是否为本地调用
     *
     * @param ip
     * @return
     */
    public static Boolean isLocalAddress(String ip) {
        if (StringUtils.isNotEmpty(ip)) {
            return ip.equals("localhost") || ip.equals("127.0.0.1");
        } else {
            return false;
        }
    }

    public static HttpServletRequest getRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            return null;
        }
        return ((ServletRequestAttributes) requestAttributes).getRequest();
    }

    public static Long getTenantIdFromRequest() {
        String sTenantId = getFromHeader(BaseConstant.TENANT_ID);
        return StringUtils.isBlank(sTenantId) ? null : Long.valueOf(sTenantId);
    }

    public static String getTokenFromRequest(boolean isThrowException) {
        HttpServletRequest request = getRequest();
        return request == null ? null : getTokenFromRequest(request, isThrowException);
    }

    /**
     * 获取当前请求的token
     *
     * @param request
     * @return
     */
    public static String getTokenFromRequest(HttpServletRequest request, boolean isThrowException) {
        //1.从请求头中获取token
        String authToken = request.getHeader(BaseConstant.AUTH_HEADER);
        if (StringUtils.isNotBlank(authToken)) {
            authToken = authToken.substring("Bearer ".length());
            return authToken;
        }
        //2.从cookie获取
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("token")) {
                    authToken = cookie.getValue();
                    return authToken;
                }
            }
        }
        //3.从requestparameter里面取
        authToken = request.getParameter("token");
        if (StringUtils.isNotBlank(authToken)) {
            return authToken;
        }

        if (isThrowException) {
            throw new TokenInvalidException("token为空");
        }

        return null;
    }

    public static String getFromHeader(String key) {
        HttpServletRequest request = getRequest();
        return request == null ? null : request.getHeader(key);
    }

    public static void setAttribute(String key, Object value) {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return;
        }
        attributes.setAttribute(key, value, RequestAttributes.SCOPE_REQUEST);
    }

    public static Object getAttribute(String key) {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return null;
        }
        return attributes.getAttribute(key, RequestAttributes.SCOPE_REQUEST);
    }

    // get 请求
    public static String httpGet(String url, Header[] headers) throws Exception {
        HttpUriRequest uriRequest = new HttpGet(url);
        if (null != headers) {
            uriRequest.setHeaders(headers);
        }
        CloseableHttpClient httpClient = null;
        try {
            httpClient = declareHttpClientSSL(url);
            CloseableHttpResponse httpresponse = httpClient.execute(uriRequest);
            HttpEntity httpEntity = httpresponse.getEntity();
            String result = EntityUtils.toString(httpEntity, REQ_ENCODEING_UTF8);
            return result;
        } catch (ClientProtocolException e) {
            out.println(String.format("http请求失败，uri{%s},exception{%s}", new Object[]{url, e}));
        } catch (IOException e) {
            out.println(String.format("IO Exception，uri{%s},exception{%s}", new Object[]{url, e}));
        } finally {
            if (null != httpClient) {
                httpClient.close();
            }
        }
        return null;
    }

    // post 请求
    public static String httpPost0(String url, String params) throws Exception {
        HttpPost post = new HttpPost(url);
        post.addHeader("Content-Type", "application/x-www-form-urlencoded");
        // 设置传输编码格式
        StringEntity stringEntity = new StringEntity(params, REQ_ENCODEING_UTF8);
        stringEntity.setContentEncoding(REQ_ENCODEING_UTF8);
        post.setEntity(stringEntity);
        HttpResponse httpresponse = null;
        CloseableHttpClient httpClient = null;
        try {
            httpClient = declareHttpClientSSL(url);
            httpresponse = httpClient.execute(post);
            HttpEntity httpEntity = httpresponse.getEntity();
            String result = EntityUtils.toString(httpEntity, REQ_ENCODEING_UTF8);
            return result;
        } catch (ClientProtocolException e) {
            out.println(String.format("http请求失败，uri{%s},exception{%s}", new Object[]{url, e}));
        } catch (IOException e) {
            out.println(String.format("IO Exception，uri{%s},exception{%s}", new Object[]{url, e}));
        } finally {
            if (null != httpClient)
                httpClient.close();
        }
        return null;
    }

    // post 请求
    public static String httpPost(String url, Header[] headers, String params) throws Exception {
        HttpPost post = new HttpPost(url);
        if (null != headers) {
            post.setHeaders(headers);
        }
        post.addHeader("Content-Type", "application/json;charset=" + REQ_ENCODEING_UTF8);
        // 设置传输编码格式
        StringEntity stringEntity = new StringEntity(params, REQ_ENCODEING_UTF8);
        stringEntity.setContentEncoding(REQ_ENCODEING_UTF8);
        post.setEntity(stringEntity);
        HttpResponse httpresponse = null;
        CloseableHttpClient httpClient = null;
        try {
            httpClient = declareHttpClientSSL(url);
            httpresponse = httpClient.execute(post);
            HttpEntity httpEntity = httpresponse.getEntity();
            String result = EntityUtils.toString(httpEntity, REQ_ENCODEING_UTF8);
            return result;
        } catch (ClientProtocolException e) {
            out.println(String.format("http请求失败，uri{%s},exception{%s}", new Object[]{url, e}));
        } catch (IOException e) {
            out.println(String.format("IO Exception，uri{%s},exception{%s}", new Object[]{url, e}));
        } finally {
            if (null != httpClient)
                httpClient.close();
        }
        return null;
    }

    private static CloseableHttpClient declareHttpClientSSL(String url) {
        if (url.startsWith("https://")) {
            return sslClient();
        } else {
            return HttpClientBuilder.create().setConnectionManager(httpClientConnectionManager).build();
        }
    }

    private static CloseableHttpClient sslClient() {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(X509Certificate[] xcs, String str) {
                }

                public void checkServerTrusted(X509Certificate[] xcs, String str) {
                }
            };
            ctx.init(null, new TrustManager[]{tm}, null);
            SSLConnectionSocketFactory sslConnectionSocketFactory = SSLConnectionSocketFactory.getSocketFactory();
            return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (KeyManagementException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取本次请求的接口调用地址
     *
     * @return requestUri地址
     */
    public static String getRequestURI() {
        HttpServletRequest request = getRequest();
        return request == null ? null : request.getRequestURI();
    }

    /**
     * 获取HTTP请求参数
     *
     * @param name
     * @return
     */
    public static String getParameter(String name) {
        HttpServletRequest request = getRequest();
        return request == null ? null : request.getParameter(name);
    }

    /**
     * 获取本次请求的接口调用地址的host
     *
     * @return requestUri地址
     */
    public static String getRequestHost() {
        String url = getRequestURI();
        return getHost(url);
    }

    public static String getHost(String url) {
        if (!(StringUtils.startsWithIgnoreCase(url, "http://") || StringUtils
                .startsWithIgnoreCase(url, "https://"))) {
            url = "http://" + url;
        }

        String returnVal = StringUtils.EMPTY;
        try {
            Pattern pattern = compile("(?<=//|)((\\w)+\\.)+\\w+");
            Matcher m = pattern.matcher(url);
            if (m.find()) {
                returnVal = m.group();
            }

        } catch (Exception e) {
            log.error("获取host失败 ==》 {}", e.getMessage(), e);
            return returnVal;
        }
        if ((StringUtils.endsWithIgnoreCase(returnVal, ".html") || StringUtils
                .endsWithIgnoreCase(returnVal, ".htm"))) {
            returnVal = StringUtils.EMPTY;
        }
        return returnVal;
    }

    public static String getBaseUrl(String originalUrl) throws Exception {
        URL url = StringUtils.contains(originalUrl, "://") ? new URL(originalUrl)
                : new URL(URLDecoder.decode(originalUrl, "UTF-8"));

        StringBuilder baseUrl = new StringBuilder(url.getProtocol())
                .append("://").append(url.getHost());
        if (url.getPort() > 0) {
            baseUrl.append(":").append(url.getPort());
        }

        return baseUrl.toString();
    }
}
